<?php

require_once('../include/GeneralTop.php');
require('../include/class/db.php');
require("../include/lib/fckeditor/fckeditor.php");
require('../include/lib/phpmailer/class.phpmailer-lite.php');

if (!$content_admin) {
	die('<div style="text-align:center">Permission denied...</div>');
}

$db = new db;

if ((isset($_POST["submit"])) || isset($_GET['mail'])) {
    /*    
    header("location:".$_SERVER['PHP_SELF']."?result=suc");
    */
    //print_r($_POST['sendto']);
    
	$get = false;
	if(isset($_GET['mail'])) {
		$get_mail = substr($_GET['mail'], 0, -1);
		$get_mail = explode(",", $get_mail);
		$get = true;
	}
	$sendto = isset($_POST['sendto']) ? $_POST['sendto'] : $get_mail;
    $addr_arr = array();
    
    //0 means invalid email, 1 means valid email, 2 means user unsubscribe
    if(!$get) {
    	echo "Adding following emails to query...<br>";
    }
    if(in_array(1, $sendto)) {
    	$sql = "select member_id, member_login, member_name, Email_account, unsubscribe_token from member_info where if_send_newsletter=1";
		$res = $db->query($sql);
		while($row = $db->fetch($res)) {
			if(ValidateAddress($row['Email_account'])) {
				if(!$get) {
			    	echo '&nbsp;- '.$row['Email_account'].'<br>';
			    }
				$addr_arr[] = array('name' => $row['member_name'],
									'email' => $row['Email_account'],
									'status' => 0,
									'token' => $row['unsubscribe_token']);
			}
			else {
				$upd = "update member_info set if_send_newsletter=0 where member_id='".$row['member_id']."'";
				$db->query($upd);
			}
		}
		$sql = "select ECId, nickname, ECEmail, unsubscribe_token from emailcollection where status=1";
		$res = $db->query($sql);
		while($row = $db->fetch($res)) {
			if(ValidateAddress($row['ECEmail'])) {
				if(!$get) {
			    	echo '&nbsp;- '.$row['ECEmail'].'<br>';
			    }
				$addr_arr[] = array('name' => $row['nickname'],
									'email' => $row['ECEmail'],
									'status' => 0,
									'token' => $row['unsubscribe_token']);
			}
			else {
				$upd = "update emailcollection set status=0 where ECId='".$row['ECId']."'";
				$db->query($upd);
			}
		}
		//maybe forum
    }
    else {
	    if(in_array(2, $sendto)) {
	    	$sql = "select member_id, member_login, member_name, Email_account, unsubscribe_token from member_info where if_send_newsletter=1";
    		$res = $db->query($sql);
    		while($row = $db->fetch($res)) {
    			if(ValidateAddress($row['Email_account'])) {
	    			if(!$get) {
				    	echo '&nbsp;- '.$row['Email_account'].'<br>';
				    }
	    			$addr_arr[] = array('name' => $row['member_name'],
	    								'email' => $row['Email_account'],
										'status' => 0,
										'token' => $row['unsubscribe_token']);
				}
				else {
					$upd = "update member_info set if_send_newsletter=0 where member_id='".$row['member_id']."'";
					$db->query($upd);
				}
    		}
	    }
	    if(in_array(3, $sendto)) {
	    	$sql = "select ECId, nickname, ECEmail, unsubscribe_token from emailcollection where status=1";
    		$res = $db->query($sql);
    		while($row = $db->fetch($res)) {
    			if(ValidateAddress($row['ECEmail'])) {
	    			if(!$get) {
				    	echo '&nbsp;- '.$row['ECEmail'].'<br>';
				    }
	    			$addr_arr[] = array('name' => $row['nickname'],
	    								'email' => $row['ECEmail'],
										'status' => 0,
										'token' => $row['unsubscribe_token']);
				}
				else {
					$upd = "update emailcollection set status=0 where ECId='".$row['ECId']."'";
					$db->query($upd);
				}
    		}
	    }
	    if(in_array(4, $sendto)) { 
	    	//maybe we need this for forum...
	    }		   
    }
    
    if(isset($_POST['extra']) && '' != $_POST['extra']) {
    	$dummy = explode(";", $_POST['extra']);
    	foreach($dummy as $_key => $_value) {    		
    		$dummy_sub = explode("^", trim($_value));
    		if(!$get) {
		    	echo '&nbsp;- '.$dummy_sub[1].'<br>';
		    }
    		if(ValidateAddress($dummy_sub[1])) {
	    		$addr_arr[] = array('name' => $dummy_sub[0],
	    							'email' => $dummy_sub[1],
									'status' => 0);
    		}
    	}
    }
    if(!$get) {
    	echo "Done...<br><br>";
    }
    
    if(isset($_GET['extra']) && '' != $_GET['extra']) {
    	$dummy = explode(";", $_GET['extra']);
    	foreach($dummy as $_key => $_value) {
    		$dummy_sub = explode("^", trim($_value));
    		if(ValidateAddress($dummy_sub[1])) {
	    		$addr_arr[] = array('name' => $dummy_sub[0],
	    							'email' => $dummy_sub[1],
									'status' => 0);
    		}
    	}
    }
    
    //echo '<pre>';
    //print_r($addr_arr);
    //echo '</pre>';
    //die();
   	$email_count = count($addr_arr);
    if(!$get) {
		//$addr_arr = array(array('name' => 'joe qiao', 'email' => 'mynamesucks@163.com', 'status' => 0),
		//				  array('name' => 'jo qiao', 'email' => 'joqiao@ebay.com', 'status' => 0));
		//print_r($addr_arr);
		//die();
		//save the mail addresses on server
		$batch_name = date("YmdHis").time();
		$amount = $_POST['amount'];
		$amount = 7; //for testing
		if('all' == $amount) {
			$addr_arr = array($addr_arr);
		}
		else {
			$addr_arr = array_chunk($addr_arr, $amount);
		}
		//echo '<pre>';
	    //print_r($addr_arr);
	    //echo '</pre>';
	    //die();
	    
	    $i = 0;
	    foreach($addr_arr as $_key => $_value) {
			$batch_name_sub = $batch_name.'_'.$_key;
			$log_file = $batch_name_sub.'_total';
			file_put_contents(NEWSLETTER_LOG_MAIL_ADDRESS_PATH.'/'.$log_file, serialize($_value));
			//insert log table
			if(0 === (int)$_POST['start_time']) {
				if(0 === (int)$i) {
					$start_t = date("Y-m-d H:i:s");
				}
				else {
					$start_t = $start_next;
				}
				$at_once = true;
			}
			else {
				if(0 === (int)$i) {
					$start_t = $_POST['start_time'].":00";
				}
				else {
					$start_t = $start_next;
				}
				$at_once = false;
			}
			
			$start_next = date("Y-m-d H:i", strtotime($start_t) + 1800).":00";
			$insertSQL = sprintf("INSERT INTO newsletter_log (email_addr, newsletter_title, newsletter_content,
									batch, total, failed, start_time) VALUES (%s, %s, %s, %s, %d, %d, %s)",
		                       GetSQLValueString($log_file, "text"),
		                       GetSQLValueString($_POST['title'], "text"),
		                       GetSQLValueString(stripslashes($_POST['FCKeditor1']), "text"),
		                       GetSQLValueString($batch_name_sub, "text"),
		                       GetSQLValueString($email_count, "int"),
		                       GetSQLValueString(0, "int"),
		                       GetSQLValueString($start_t, "text")
		                       );
		    //echo $insertSQL.'<br>';
		    $db->query($insertSQL);
		    if(0 === (int)$i) {
		    	$insert_id = $db->insert_id();
		    	$batch_name_failed = $batch_name_sub.'_failed';
		    }
		    
		    $i ++; //next batch
	    }

		//send mails
		if($at_once) {
			try {
				$mail = new PHPMailerLite(true); //New instance, with exceptions enabled
			
				//$body             = file_get_contents('contents.html');
			
				$mail->AddReplyTo(ADMIN_MAIL_ADDRESS, ADMIN_MAIL_NAME);
			
				$mail->SetFrom(ADMIN_MAIL_ADDRESS, ADMIN_MAIL_NAME);
			
				$to = $addr_arr[0];
				echo "Start sending....<br>";
				foreach($to as $_key => $_value) {
					//print_r($_value);
					$mail->AddAddress($_value['email'], $_value['name']);		
			  
					$mail->IsMail();
					$mail->CharSet = "utf-8";
				  
					$mail->Subject  = $_POST['title'];
				
					$mail->AltBody    = $_POST['title']; // optional, comment out and test
					$mail->WordWrap   = 80; // set word wrap
					
					//mails have different unsubscribe address
					if(isset($_value['token']) && '' != $_value['token']) {
						$unsubscribe_address = MAIL_UNSUBSCRIBE_ADDRESS.'?token='.$_value['token'];					
						$body = stripslashes($_POST['FCKeditor1']);
						$body = str_replace(array('[unsubsribe_link]', '[/unsubsribe_link]'), 
											array('<a href="'.$unsubscribe_address.'" target="_BLANK">', '</a>'), 
											$body);
						//echo $body.'<br>';
					}
					else {
						$body = str_replace(array('[unsubsribe_link]', '[/unsubsribe_link]'), 
											array('<span style="display:none">', '</span>'), 
											$body);
					}
					$body = preg_replace('/\\\\/','', $body); //Strip backslashes
					
					$mail->MsgHTML($body);
				
					$mail->IsHTML(true); // send as HTML
					
					$mail->Send();

					$mail->ClearAddresses();
  					$mail->ClearAttachments();
				}
				
				$sel_fail = "select failed from newsletter_log where id=$insert_id";
				$sel_fail_res = $db->query($sel_fail);
				$sel_fail_row = $db->fetch($sel_fail_res);
				$fail = $sel_fail_row['failed'];
				$suc = $email_count - $fail;
				echo "Done...<br>
						 $email_count in all, <font color='green'>$suc</font> succeed, <font color='red'>$fail</font> failed.<br><br>";
				
				$end = "update newsletter_log set end_time='".date("Y-m-d H:i:s")."', status=2 where id=$insert_id";
				$db->query($end);
			} catch (phpmailerException $e) {
				echo $e->errorMessage();
				echo "<font color='red'>Error occured...</font><br><br>";
			}			
			$end = "update newsletter_log set end_time='".date("Y-m-d H:i:s")."', status=0 where id=$insert_id";
			$db->query($end);
		}
		
		echo "Sending newsletter process finished.<br>
				<input type='button' value=' back ' onclick='window.location.href=\"SendNewsletter.php\"'>";
		exit();
    }
}

include('AdminPanel.php');
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Send Newsletter</title>
<script src="../include/js/calendar.js" type="text/javascript"></script>
</head>

<body>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="form1" id="form1" onsubmit="return check_mail();">
  <table align="center" width="70%">
    <?php
    if($_GET['result'] && 'suc' == $_GET['result']) {
    ?>
    <tr valign="baseline">
      <td colspan="2" nowrap="nowrap" align="center"><font color="green">Send finish...</font></td>
    </tr>
    <?php
    }
    ?>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right"></td>
      <td nowrap="nowrap" align="left"><input type="button" id="button" onclick="window.location.href='AddNewsletter.php'" value="Add new newsletter"></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Select newsletter:</td>
      <td>
		<select name="newsletter" onchange="window.location.href='?id='+this.options[this.selectedIndex].value;">
		  <option value="-1">--Select--</option>
		  <?php
		  $sql = "select * from newsletter order by cre_date";
		  $res = $db->query($sql);
		  while($row = $db->fetch($res)) {
		      if(isset($_GET['id']) && $_GET['id'] == $row['id']) {
		  	      echo '<option value="'.$row['id'].'" selected>'.$row['title'].'</option>';
		      }
		      else {
		      	  echo '<option value="'.$row['id'].'">'.$row['title'].'</option>';
		      }
		  }
	      ?>
	    </select>
	    &nbsp;
	    <?php
	    if(isset($_GET['id']) && -1 != $_GET['id']) {
	    	echo '<a href="EditNewsletter.php?id='.$_GET['id'].'">Edit this newsletter</a>';
	    }
	    ?>
	  </td>
    </tr>
    <?php
    if(isset($_GET['id']) && -1 != $_GET['id']) {
    	$newsletter_sql = "select * from newsletter where id=".$_GET['id'];
    	$newsletter_res = $db->query($newsletter_sql);
    	$newsletter_row = $db->fetch($newsletter_res);
    ?>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Send to:</td>
      <td style="border:#ccc solid 1px; line-height:30px; padding:10px;">
      	<label for="sendto">
      	<?php
      	if($get && isset($sendto)) {
	      	$check1 = '';
		    $check2 = '';
		    $check3 = '';
		    $check4 = '';
		    if(in_array(1, $sendto)) {
		    	$check1 = 'checked';
		    }
		    if(in_array(2, $sendto)) {
		    	$check2 = 'checked';
		    }
		    if(in_array(3, $sendto)) {
		    	$check3 = 'checked';
		    }
		    if(in_array(4, $sendto)) {
		    	$check4 = 'checked';
		    }
      	}
		?>
	  	<input type="checkbox" name="sendto[]" id="sendto" value="1" <?php echo $check1?>>all &nbsp;
	  	<input type="checkbox" name="sendto[]" id="sendto" value="2" <?php echo $check2?>>website member &nbsp;
	  	<input type="checkbox" name="sendto[]" id="sendto" value="3" <?php echo $check3?>>website email collection &nbsp;
	  	<input type="checkbox" name="sendto[]" id="sendto" value="4" <?php echo $check4?>>forum &nbsp;
	  	</label>
	  	<br>
	  	Extra: <input type="text" name="extra" id="extra" size="70" value="<?php echo $_GET['extra']?>"> <font color="red">10 addresses at most</font> 
	  	<br>example:joe qiao^mynamesucks@163.com;Tom Hanks^another_email@gmail.com;...
	  	<br>
	  	<input type="button" value=" Done " onclick="check_mail(2);"
	  	<?php
	  	if(isset($email_count)) {
	  		if(0 < $email_count) {
	  			echo '<br>
					  <font color="red">'.$email_count.' emails will be sent out.<br>
					  Select an amount of mails for each batch to split them into several batches. Interval time of batches is '.(MAIL_BATCH_INTERVAL/60).' minutes.</font><br>';
				echo '<select name="amount">
						<option value="all">send all in one batch</option>
						<option value="50">50</option>
						<option value="100">100</option>
						<option value="200">200</option>
						<option value="500">500</option>
						<option value="1000">1000</option>
						<option value="2000">2000</option>
						<option value="5000">5000</option>
						<option value="10000">10000</option>';
	  		}
	  		else {
	  			echo '<br><br>
					  <font color="red">There is no emails will be sent out.</font>';
	  		}
	  	}
	  	?>
	  </td>
    </tr>
    <tr>
      <td></td>
      <td><hr style="color: #ccc; height:1px;"></td>
    </tr>
    <tr>
      <td></td>
      <td><font color="red">Title and content below is editable before sent. It will be the final version that members will receive.
      						<br>The modifications will only be available on this occasion and will not be saved for this newsletter.
      						<br>If you want to edit this newsletter, please click <a href="EditNewsletter.php?id=<?php echo $_GET['id']?>">here</a>.</font></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">title:</td>
      <td><input type="text" name="title" value="<?php echo $newsletter_row['title']?>" size="50" /></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right" valign="top">Content:</td>
      <td>
      <?php
	  $oFCKeditor = new FCKeditor('FCKeditor1') ;
	  $oFCKeditor->BasePath = FCKEDITOR_BASE_PATH;
	  $oFCKeditor->Height = 600;
	  $oFCKeditor->Value = $newsletter_row['content'];
	  $oFCKeditor->Create();
	  ?>
      </td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Start time</td>
      <td>
      	<input type="text" name="start_time" value="0"> 
      	<br><font color="red">When the batches will be start. 0 means at once. Time format: "2010-02-03 00:00" to "2010-02-03 23:59".
      	<br>If there are more than 1 batch, first will be start at the start time and second will be start <?php echo (MAIL_BATCH_INTERVAL/60)?> minutes later and third <?php echo (MAIL_BATCH_INTERVAL/60*2)?> minutes later...</font>
      </td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">&nbsp;</td>
      <td>
      	<input type="submit" name="submit" id="submit" value="Send..." />
      </td>
    </tr>
    <?php
    }
    ?>
  </table>
</form>
<p>&nbsp;</p>
</body>
</html>

<script language="JavaScript" type="text/javascript">
function check_mail(action) {
	var checkbox = document.form1.sendto;
	var len = checkbox.length;
    var checked = false;
	var str = '';
	  
    for (i = 0; i < len; i++)
    {
        if (checkbox[i].checked == true)
        {
            str += checkbox[i].value+",";
            checked = true;
        }
    }
    if (!checked && document.getElementById("extra").value == '')
    {
        alert("You must check a checkbox or input an extra mail address.");
        return false;
    }
	
	if(action){   
        //alert(str);
        window.location.href="?id=<?php echo $_GET['id']?>&mail="+str+"&extra="+document.getElementById('extra').value;
    }
	
    return true;
}
</script>